<template>
  <!-- 精准获客 -->
  <div class="jzhk">
    <!-- 筛选栏 -->
    <div class="query">
      <my-button type="add" bgc="#E4ECFF" fontColor="#649AF9" @click="handleClickAdd">添加</my-button>
      <my-button type="del" bgc="#fff" border="#DCDCDF" fontColor="#88898E" @click="handleClickDel">删除</my-button>
      <my-button bgc="#387CF7" @click="handleClickWords">排名词</my-button>
      <div v-if="userInfo" class="desc">
        当前套餐最多可添加关键词
        <span v-if="userInfo.taocaninfo">DY: {{ userInfo.taocaninfo.dykeylimit }}</span>
        <span v-if="userInfo.taocaninfo">KS: {{ userInfo.taocaninfo.kskeylimit }}</span>
        <span v-if="userInfo.taocaninfo">
          XHS: {{ userInfo.taocaninfo.xhskeylimit }}</span>
      </div>
    </div>
    <!-- 主体 -->
    <div class="container">
      <!-- 操作栏 -->
      <div class="action">
        <div class="list-refresh">
          <my-dropdown-list :list="tableColumn" @change="changeTableColumn"></my-dropdown-list>
          <div class="iconfont icon" @click="refresh">&#xe74a;</div>
        </div>
      </div>
      <!-- 表格 -->
      <div class="table">
        <el-table border v-if="tableHeight" @selection-change="selectionChange" :data="dataSource" :height="tableHeight"
          row-class-name="row-class-name" header-row-class-name="header-row-class-name" style="width: 100%">
          <el-table-column type="selection" width="80"> </el-table-column>
          <el-table-column prop="taskname" label="任务名称" min-width="80">
          </el-table-column>

          <el-table-column prop="by_time" label="截止时间" min-width="80">
          </el-table-column>

          <el-table-column prop="status" label="状态" width="120">
            <template slot-scope="scope">
              <my-switch :value.sync="scope.row.status" @changeSwitchValue="changeSwitchValue(scope.row)"></my-switch>
            </template>
          </el-table-column>

          <el-table-column prop="createtime" label="创建时间" width="100">
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <div class="slot-row">
                <my-button bgc="#FFEEEE" border="#FADBDB" fontColor="#F78385" @click="deleteRow(scope.row)">删除
                </my-button>
                &nbsp;&nbsp;
                <my-button bgc="#4dff3f" border="#4dff3f" fontColor="#FFF" @click="editRow(scope.row)">编辑
                </my-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <div class="page">
        <el-pagination background :current-page="currentPage" :page-size="pageSize" :page-sizes="[15,25,30]"
          layout="total,sizes, prev, pager, next, jumper" :total="total" @current-change="handleCurrentChange"
          @size-change="handleSizeChange">
        </el-pagination>
      </div>
    </div>
    <!-- ---------------- 弹窗 ---------------- -->
    <!-- 排名词 -->
    <el-dialog :visible.sync="dialogVisible" :show-close="false" width="50%" class="rank-words">
      <div class="header">
        <div class="title">排名词设置</div>
        <div class="tatals">当前排名词总数为【{{ tatals }}】个</div>
        <div class="iconfont icon" @click="dialogVisible = false">&#xe608;</div>
      </div>
      <div class="body">
        <div v-for="(item, key) in rankWords" :key="key" class="list-block">
          <div class="label">
            <div class="text">{{ item.label }}</div>
            <my-button v-if="item.showBtn" :bgc="item.btn.bgc" :fontColor="item.btn.fontColor" @click="showDialog(key)">
              {{ item.btn.btnText }}
            </my-button>
          </div>
          <textarea id="" :value="item.value" class="text-area" @input="onTextareaInput($event, key)"></textarea>
        </div>
      </div>
      <div class="footer">
        <my-button bgc="#f7d264_#f79844" @click="addRankWords">确定</my-button>
        <my-button bgc="#f7d264_#f79844" @click="dialogVisible = false">关闭</my-button>
      </div>
    </el-dialog>
    <!-- 排名词 选择地区 -->
    <el-dialog :visible.sync="showRegion" :show-close="false" width="40%" class="region-list">
      <div class="header">
        <div class="title">关键词工具 - 选择地区</div>
        <div class="iconfont icon" @click="showRegion = false">&#xe608;</div>
      </div>
      <div class="body">
        <my-region-list :list="regionList" @handleClickRow="handleClickRow" @handleClickCol="handleClickCol">
        </my-region-list>
      </div>
      <div class="footer">
        <my-button bgc="#b0ca71" fontColor="#fff" @click="selectAllRegion">{{
          isSelectAllByRegion ? "全选" : "取消全选"
        }}</my-button>
        <my-button bgc="#f8b862" @click="confirmRegion">确定</my-button>
      </div>
    </el-dialog>
    <!-- 排名词 选择后缀 -->
    <el-dialog :visible.sync="showSuffix" :show-close="false" width="40%" class="suffix-list">
      <div class="header">
        <div class="title">关键词工具 - 选择后缀</div>
        <div class="iconfont icon" @click="showSuffix = false">&#xe608;</div>
      </div>
      <div class="body">
        <div v-for="(item, index) in suffixList" :key="index" class="list-item">
          <div class="radio" :class="{ active: item.checked }" @click="handleClickSuffix(item, index)"></div>
          <div class="label">
            {{ item.label }}
          </div>
        </div>
      </div>
      <div class="footer">
        <my-button bgc="#b0ca71" fontColor="#fff" @click="selectAllSuffix">{{
          isSelectAllBySuffix ? "全选" : "取消全选"
        }}</my-button>
        <my-button bgc="#f8b862" @click="confirmSuffix">确定</my-button>
      </div>
    </el-dialog>
    <!-- 确认弹窗 -->
    <my-dialog-confirm :show.sync="showConfirm" @confirm="confirmDelete"></my-dialog-confirm>
  </div>
</template>

<script>
  import myButton from "@/components/myButton.vue";
  import myForm from "@/components/myForm.vue";
  import mySwitch from "@/components/mySwitch.vue";
  import myInput from "@/components/myInput.vue";
  import myDropdownList from "@/components/myDropdownList.vue";
  import mySearchInput from "@/components/mySearchInput.vue";
  import myRegionList from "../components/myRegionList.vue";
  import myDialogConfirm from "@/components/myDialogConfirm.vue";

  export default {
    components: {
      myButton,
      myForm,
      mySwitch,
      myInput,
      myDropdownList,
      mySearchInput,
      myRegionList,
      myDialogConfirm,
    },
    data() {
      return {
        tatals: "",
        dialogVisible: false,
        showRegion: false,
        showSuffix: false,
        showConfirm: false,
        placeQuery: {
          title: {
            type: "input",
            label: "名称",
            value: "",
            placeholder: "请输入名称",
          },
          user: {
            type: "input",
            label: "城市",
            value: "",
            placeholder: "请输入城市",
          },
          search_place: {
            type: "button",
            bgc: "#ee1e4f",
            btnText: "搜索",
          },
        }, // 地点弹窗搜索条件
        searchValue: "",
        type: "all",
        typeList: [{
            name: "全部",
            label: "全部",
            value: "all"
          },
          {
            name: "抖音",
            label: "DY",
            value: "0"
          },
          {
            name: "快手",
            label: "KS",
            value: "10"
          },
          {
            name: "小红书",
            label: "XHS",
            value: "20",
          },
        ],
        dataSource: [],
        selectedRow: {},
        tableColumn: {
          keyword: {
            show: true,
            text: "关键词",
          },
          dispensenum: {
            show: true,
            text: "商机数",
          },
          type: {
            show: true,
            text: "平台",
          },
          status: {
            show: true,
            text: "状态",
          },
          createtime: {
            show: true,
            text: "修改时间",
          },
        },
        tableHeight: 0,
        currentPage: 1,
        pageSize: 15,
        total: 300,
        haoKanForm: {
          appid: {
            label: "APP ID",
            value: "",
            required: true,
            placeholder: "",
          },
          name: {
            label: "昵称",
            value: "",
            required: true,
            placeholder: "",
          },
          token: {
            label: "Token",
            value: "",
            required: true,
            placeholder: "",
          },
        },
        regionList: [], // 选择地区列表
        suffixList: [], // 后缀列表
        isSelectAllByRegion: true, // 是否全选
        isSelectAllBySuffix: true, // 是否全选
        rankWords: {
          diqu: {
            label: "地区",
            showBtn: true,
            btn: {
              bgc: "#fef2d8",
              fontColor: "#e3a827",
              btnText: "选择地区",
            },
            value: "",
          },
          zhuci_new: {
            label: "关键词",
            value: "",
          },
          houzhui: {
            label: "后缀",
            showBtn: true,
            btn: {
              bgc: "#fef2d8",
              fontColor: "#e3a827",
              btnText: "选择后缀",
            },
            value: "",
          },
        },
        timer: null,
        userInfo: null,
        selectedRows: [],
      };
    },
    watch: {
      type: {
        handler(val) {
          this.currentPage = 1;
          this.dataSource = [];
          this.getData();
        },
      },
    },
    mounted() {
      this.tableHeight = document.querySelector(".table").offsetHeight;
      window.onresize = () => {
        clearTimeout(this.timer);
        this.timer = setTimeout(() => {
          this.tableHeight = document.querySelector(".table").offsetHeight;
        }, 500);
      };
      this.getData();
      this.userInfo = JSON.parse(window.localStorage.getItem("person"));
    },
    beforeDestroy() {
      window.onresize = null;
    },
    methods: {
      async getData() {
        let filter = {};
        if (this.type != "all") {
          filter.type = this.type;
        }
        if (this.searchValue != "") {
          filter.keyword = this.searchValue;
        }

        let res = await this.$api.automaticrelease({
          page: this.page,
          limit: this.limit,
        });
        if (res.code == 0) {
          this.dataSource = res.data
          this.total = res.count
        }
      },

      selectionChange(selection) {
        this.selectedRows = selection;
      },

      //删除
      async deleteRow(data) {
        this.$confirm('确定删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let res = this.$api.automaticrdelete({
            id: data.id,
          });
          let b = res.then((v) => {
            if (v.code == 1) {
              this.getData();
            } else {
              return this.$confirm(v.msg);
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //跳转到编辑
      editRow(id) {
        window.sessionStorage.removeItem("tmpl");
        this.$router.push({
          path: "/wdsp/exitautomaticrelease",
          query: {
            id: id.id
          }
        });
      },
      handleClickDel() {
        if (!this.selectedRows.length) {
          return this.$message("请先选择");
        }
        this.showConfirm = true;
      },
      // 确认删除
      async confirmDelete() {
        await this.$api.automaticrdelete({
          id: this.selectedRows.map((v) => v.id),
        });
        this.showConfirm = false;
        this.getData();
      },
      // 页码跳转
      handleCurrentChange(page) {
        this.currentPage = page;
        this.getData();
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.getData();

      },
      // 刷新
      refresh() {
        this.currentPage = 1;
        this.dataSource = [];
        this.getData();
      },
      handleTableColVal(val) {
        let re = this.typeList.find((v) => v.value == val);
        return re.label;
      },
      // 打开 确认弹窗
      // deleteRow(row) {
      //   this.selectedRow = row;
      //   this.showConfirm = true;
      // },
      // 添加
      async handleClickAdd() {
        window.sessionStorage.removeItem("tmpl");
        this.$router.push({
          name: "addautomaticrelease"
        });
      },
      // 修改状态
      async changeSwitchValue(row) {
        await this.$api.modify({
          id: row.id,
          field: "status",
          value: row.status ? 0 : 1,
        });
        this.getData();
      },
      // 商机数详情
      toXsPage(row) {
        this.$router.push({
          path: "/jzhk/xs",
          query: {
            id: row.id
          }
        });
      },
      // 获取排名词 以及后缀列表
      async handleClickWords() {
        let res = await this.$api.jzhk_getKeywordList({
          type: "qt0723",
        });
        if(res.code == 30001){
          this.$message({
            type: "warning",
            message: res.msg,
          });
          return false
        }
        let suffix = res.houzhui_new.split("|");
        this.suffixList = suffix.map((v) => {
          return {
            label: v,
          };
        });
        this.isSelectAllBySuffix = true;
        if(res.zhuci_new == null){
          let diqu = 0;
          let zhuci = 0;
          let houzhui = 0;
          let tatal =
            diqu * zhuci + zhuci * houzhui + diqu * zhuci * houzhui + zhuci;
          this.tatals = tatal;
          console.log(this.tatals, "2222");
          this.dialogVisible = true;
        }else{
         for (let key in this.rankWords) {
           this.rankWords[key].value = res[key];
           this.rankWords[key].arrValue = res[key] == null ? '' :  res[key].split("\n");
         }
         console.log(this.rankWords, "this.rankWords");
         let diqu = this.rankWords.diqu.arrValue.length;
         let zhuci = this.rankWords.zhuci_new.arrValue.length;
         let houzhui = this.rankWords.houzhui.arrValue.length;
         let tatal =
           diqu * zhuci + zhuci * houzhui + diqu * zhuci * houzhui + zhuci;
         this.tatals = tatal;
         console.log(this.tatals, "2222");
         this.dialogVisible = true;
        }
        // for (let key in this.rankWords) {
        //   this.rankWords[key].value = res[key];
        //   this.rankWords[key].arrValue = res[key].split("\n");
        // }
        // console.log(this.rankWords, "this.rankWords");
        // let diqu = this.rankWords.diqu.arrValue.length;
        // let zhuci = this.rankWords.zhuci_new.arrValue.length;
        // let houzhui = this.rankWords.houzhui.arrValue.length;
        // let tatal =
        //   diqu * zhuci + zhuci * houzhui + diqu * zhuci * houzhui + zhuci;
        // this.tatals = tatal;
        // console.log(this.tatals, "2222");
        // this.dialogVisible = true;
      },
      // 选择地区  后缀
      async showDialog(key) {
        if (key == "diqu") {
          let res = await this.$api.jzhk_getCityList();
          res = JSON.parse(res);
          this.regionList = res.data.filter((v) => v.city.length);
          console.log(this.regionList,'regiongth')
          console.log(res.data,'res')
          this.isSelectAllByRegion = true;
          this.showRegion = true;
        }
        if (key == "houzhui") {
          this.showSuffix = true;
        }
      },
      // 修改 textarea 值
      onTextareaInput(e, key) {
        this.rankWords[key].value = e.target.value;
      },
      // 控制表格显示哪几列
      changeTableColumn(key) {
        this.tableColumn[key].show = !this.tableColumn[key].show;
      },
      // 添加排名词
      async addRankWords() {
        let res = await this.$api.jzhk_addRankWords({
          diqu: this.rankWords.diqu.value,
          zhuci: this.rankWords.zhuci_new.value,
          houzhui: this.rankWords.houzhui.value,
        });
        if (res.code == 1) {
          this.$message({
            type: res.code == 0 ? "warning" : "success",
            message: res.msg,
          });
          this.dialogVisible = false
        } else {
          this.$message({
            type: res.code == 0 ? "warning" : "success",
            message: res.msg,
          });
        }
      },
      // 选择后缀 确定
      confirmSuffix() {
        let checked = this.suffixList.filter((v) => v.checked);
        let str = "";
        for (let i = 0; i < checked.length; i++) {
          str = str + "\n" + checked[i].label;
        }
        this.rankWords.houzhui.value = this.rankWords.houzhui.value + str;
        this.showSuffix = false;
      },
      // 选择某一个后缀
      handleClickSuffix(item, index) {
        let obj = JSON.parse(JSON.stringify(this.suffixList[index]));
        obj.checked = this.suffixList[index].checked ? false : true;
        this.$set(this.suffixList, index, obj);
      },
      // 后缀全选
      selectAllSuffix() {
        for (let i = 0; i < this.suffixList.length; i++) {
          let obj = JSON.parse(JSON.stringify(this.suffixList[i]));
          obj.checked = this.isSelectAllBySuffix ? true : false;
          this.$set(this.suffixList, i, obj);
        }
        this.isSelectAllBySuffix = !this.isSelectAllBySuffix;
      },
      // 确认
      confirm() {},
      // 重置
      reset() {},
      // 选择单个城市
      handleClickCol({
        index,
        i
      }) {
        let obj = JSON.parse(JSON.stringify(this.regionList[index]));
        obj.city[i].checked = obj.city[i].checked ? false : true;
        obj.checked = obj.city.every((v) => v.checked);
        this.$set(this.regionList, index, obj);
      },
      // 选择某个省份下的所有城市
      handleClickRow(index) {
        let obj = JSON.parse(JSON.stringify(this.regionList[index]));
        obj.checked = obj.checked ? false : true;
        obj.city.forEach((item) => {
          item.checked = obj.checked;
        });
        this.$set(this.regionList, index, obj);
      },
      // 选择所有城市
      selectAllRegion() {
        this.regionList.forEach((item) => {
          item.checked = true;
        });
        for (let i = 0; i < this.regionList.length; i++) {
          let obj = JSON.parse(JSON.stringify(this.regionList[i]));
          obj.checked = this.isSelectAllByRegion ? true : false;
          obj.city.forEach((city) => {
            city.checked = this.isSelectAllByRegion ? true : false;
          });
          this.$set(this.regionList, i, obj);
        }
        this.isSelectAllByRegion = !this.isSelectAllByRegion;
      },
      // 地区选择 确定， 把checked = true 的 过滤出来 发送请求
      confirmRegion() {
        let checked = [];
        for (let i = 0; i < this.regionList.length; i++) {
          let res = this.regionList[i].city.filter((v) => v.checked);
          checked.push(...res);
        }
        let str = "";
        for (let i = 0; i < checked.length; i++) {
          str = str + "\n" + checked[i].name;
        }
        this.rankWords.diqu.value = this.rankWords.diqu.value + str;
        this.showRegion = false;
      },
    },
  };
</script>

<style lang="less" scoped>
  .jzhk {
    position: relative;
    width: 100%;
    height: 100%;
    padding: 112px 0 0px 0;
    box-sizing: border-box;
  }

  .query {
    position: absolute;
    top: 52px;
    display: flex;
    align-items: center;
    width: 100%;
    height: 52px;
    padding: 11px 45px;
    box-sizing: border-box;
    background-color: #fff;

    /deep/ .el-select {
      width: 150px;
      height: 30px;
      margin-right: 20px;

      .el-input {
        height: 100%;

        .el-input__inner {
          height: 100%;
          border: 1px solid #e7e7e7;
          border-radius: 15px;
        }

        .el-input__icon {
          line-height: normal;
        }
      }
    }

    .button {
      margin-left: 12px;
      width: 75px;
      height: 30px;
      font-size: 13px;
      font-weight: bold;
    }

    .desc {
      color: #777;
      font-size: 14px;
      margin-left: 20px;

      span {
        margin-right: 10px;
      }
    }
  }

  .container {
    position: relative;
    width: 100%;
    height: 100%;
    padding: 45px 0 80px 0;
    box-sizing: border-box;
    background-color: #fff;

    .action {
      position: absolute;
      left: 0;
      top: 0;
      display: flex;
      align-items: center;
      justify-content: flex-end;
      width: 100%;
      height: 45px;
      padding: 0 40px;
      box-sizing: border-box;

      .list-refresh {
        position: absolute;
        bottom: 12px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 60px;

        .icon {
          font-size: 17px;
          color: rgba(212, 212, 212);
          cursor: pointer;
        }
      }
    }

    .table {
      width: 100%;
      height: 100%;
      padding: 0 34px;
      box-sizing: border-box;

      /deep/ .header-row-class-name {
        height: 65px;

        th {
          background-color: #f0f4ff;
        }

        .cell {
          height: 100%;
          color: #333;
          text-align: center;
        }
      }

      /deep/ .row-class-name {
        height: 50px;

        .cell {
          display: flex;
          justify-content: center;
          text-align: center;

          .slot-row {
            display: flex;
            align-items: center;
            justify-content: center;

            .icon-block {
              display: flex;
              align-items: center;
              height: 18px;
              padding: 0 8px;
              border-right: 2px solid #c7c7c7;

              .icon {
                color: #333;
                font-size: 20px !important;
              }

              .number {
                color: #333;
                font-size: 16px;
              }
            }

            :last-child {
              border-right: 0;
            }
          }

          .button {
            width: 60px;
            height: 24px;
          }
        }
      }
    }
  }

  .page {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 80px;

    /deep/ .active {
      background-color: #387CF7 !important;
    }
  }

  // 弹窗样式
  .el-dialog__wrapper {
    /deep/ .el-dialog__header {
      padding: 0;
    }

    /deep/ .el-dialog__body {
      padding: 0px 0px;

      .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        font-size: 18px;
        padding: 18px 28px;
        box-sizing: border-box;
        border-bottom: 1px solid #d7d7d7;

        .title {
          font-weight: bold;
        }

        .text {
          color: #000;
        }

        .tatals {
          padding-right: 500px;
        }

        .icon {
          color: rgba(178, 178, 178);
          cursor: pointer;
          user-select: none;
        }
      }

      .footer {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20px 0 40px 10px;

        .button {
          width: 120px;
          margin-right: 20px;
        }
      }
    }

    /deep/ .el-dialog__footer {
      padding: 0;
    }
  }

  .rank-words {
    .body {
      display: flex;
      justify-content: space-between;
      width: 100%;
      padding: 0 60px 20px 60px;
      box-sizing: border-box;

      .list-block {
        width: 30%;

        .label {
          display: flex;
          align-items: center;
          height: 70px;

          .text {
            font-size: 16px;
            margin-right: 10px;
          }

          .button {
            height: 30px;
          }
        }

        .add {
          display: flex;
          align-items: center;
          justify-content: space-between;
          height: 60px;
          padding: 15px 0;
          box-sizing: border-box;

          input {
            width: 150px;
            height: 30px;
            outline: none;
            border: 1px solid #e7e7e7;
            border-radius: 5px;
            padding: 0 10px;
            box-sizing: border-box;
          }

          .button {
            height: 30px;
          }
        }

        .text-area {
          width: 100%;
          height: 400px;
          border: 1px solid #e7e7e7;
          outline: none;
          resize: none;
          overflow: auto;
          font-size: 16px;
          color: #333;
          padding: 10px;
          box-sizing: border-box;
          line-height: 24px;
        }
      }
    }
  }

  .region-list {
    .body {
      width: 100%;
      height: 430px;
    }
  }

  .suffix-list {
    .body {
      display: flex;
      align-content: flex-start;
      flex-wrap: wrap;
      width: 100%;
      height: 300px;
      padding: 10px 20px;
      box-sizing: border-box;
      overflow: auto;

      .list-item {
        display: flex;
        align-items: center;
        width: 130px;
        height: 40px;
        line-height: 40px;
        margin-right: 15px;
        margin-bottom: 15px;

        .radio {
          flex-shrink: 0;
          width: 16px;
          height: 16px;
          border-radius: 50%;
          border: 1px solid #e3a827;
          transition: all 0.1s;
          margin-right: 15px;
          cursor: pointer;

          &:hover {
            border: 1px solid #e3a827;
          }
        }

        .label {
          font-size: 16px;
        }
      }
    }
  }

  .active {
    position: relative;
    background-color: #fef2d8;

    &::after {
      content: "";
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      display: block;
      width: 7px;
      height: 7px;
      border-radius: 50%;
      background-color: #e3a827;
    }
  }
</style>
